package com.gzhryc.shared_device.bxscn.code.outside.znst;

import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.json.JsonTools;
import com.gzhryc.common.logging.Logger;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

/**
 * 中能思拓API接口
 * @version 20240130
 */
public class ZhongNengSiTuoAPIService {

    static Logger log = Logger.getLogger(ZhongNengSiTuoAPIService.class);

    static ZhongNengSiTuoAPIService me;

    public static ZhongNengSiTuoAPIService self(){
        if(me == null){
            me = new ZhongNengSiTuoAPIService();
        }
        return me;
    }

    private OutsideZNSTConfig config;

    public void initial(OutsideZNSTConfig config){
        this.config = config;
    }

    public String getToken() throws LogicException {
        if(this.config == null){
            throw new LogicException("服务未初始化");
        }
        CloseableHttpResponse response = null;
        try {
            CloseableHttpClient httpClient = HttpClients.custom().build();
            URI uri = new URIBuilder(config.getHttpDomain() + "/api/user/app/login").build();

            HttpPost httpPost = new HttpPost(uri);

            Map<String,Object> data = new HashMap<>();
            data.put("loginName",config.getName());
            data.put("password",config.getPwd());
            data.put("appCode","rent");
            String content = JsonTools.toJson(data);
            StringEntity strEntity = new StringEntity(content, ContentType.create("application/json", Consts.UTF_8));
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("中能思拓HTTP响应：" + str);
                if(JsonTools.isJsonStr(str)){
                    GetTokenResponse apiResp = JsonTools.fromJson(str, GetTokenResponse.class);
                    if(apiResp != null && 200 == apiResp.getCode() && apiResp.getData() != null){
                        return apiResp.getData().getToken();
                    }else{
                        throw new LogicException(apiResp.getMsg());
                    }
                }
            }
        } catch (Exception e) {
            log.error("中能思拓HTTP请求错误，"+ e.getMessage(), e);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public OpenOrCloseResponse sendOpenOrClose(OpenOrCloseRequest openOrCloseRequest) throws LogicException {
        if(this.config == null){
            throw new LogicException("服务未初始化");
        }
        CloseableHttpResponse response = null;
        try {
            CloseableHttpClient httpClient = HttpClients.custom().build();
            URI uri = new URIBuilder(config.getHttpDomain()  + "/api/rent/order/active").build();

            HttpPost httpPost = new HttpPost(uri);

            httpPost.setHeader("token", openOrCloseRequest.getToken());

            Map<String,Object> data = new HashMap<>();
            data.put("serialNum",openOrCloseRequest.getTradeNo());
            data.put("devId",openOrCloseRequest.getDeviceSn());
            data.put("rentalLength",openOrCloseRequest.getHour());
            String content = JsonTools.toJson(data);
            StringEntity strEntity = new StringEntity(content, ContentType.create("application/json", Consts.UTF_8));
            httpPost.setEntity(strEntity);
            
            log.info("中能思拓HTTP请求：" + content);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("中能思拓HTTP响应：" + str);
                if(JsonTools.isJsonStr(str)){
                    return JsonTools.fromJson(str, OpenOrCloseResponse.class);
                }
            }
        } catch (Exception e) {
            log.error("中能思拓HTTP请求错误，"+ e.getMessage(), e);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
    
    public OperateLightResponse sendOperateLignt(String token,String deviceSn,Integer status) throws LogicException {
        if(this.config == null){
            throw new LogicException("服务未初始化");
        }
        CloseableHttpResponse response = null;
        try {
            CloseableHttpClient httpClient = HttpClients.custom().build();
            URI uri = new URIBuilder(config.getHttpDomain()  + "/api/equip/operator/light")
            		.addParameter("equipId", deviceSn)
            		.addParameter("status", status.toString())
            		.build();

            HttpGet httpGet = new HttpGet(uri);

            httpGet.setHeader("Authorization", token);

            response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("中能思拓操作灯光HTTP响应：" + str);
                if(JsonTools.isJsonStr(str)){
                    return JsonTools.fromJson(str, OperateLightResponse.class);
                }
            }
        } catch (Exception e) {
            log.error("中能思拓操作灯光HTTP请求错误，"+ e.getMessage(), e);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}
